package com.flower8.utils;

import com.flower8.sysconfig.constants.UserConstants;
import com.flower8.model.SysAdmin;
import com.flower8.model.SysMenu;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;

import java.util.List;

/**
 * 获取当前登录账号信息工具类
 */
public class UserUtil {

	public static SysAdmin getCurrentUser() {
		SysAdmin user = (SysAdmin) getSession().getAttribute(UserConstants.LOGIN_USER);

		return user;
	}

	public static void setUserSession(SysAdmin user) {
		getSession().setAttribute(UserConstants.LOGIN_USER, user);
	}

	@SuppressWarnings("unchecked")
	public static List<SysMenu> getCurrentPermissions() {
		List<SysMenu> list = (List<SysMenu>) getSession().getAttribute(UserConstants.USER_PERMISSIONS);

		return list;
	}

	public static void setPermissionSession(List<SysMenu> list) {
		getSession().setAttribute(UserConstants.USER_PERMISSIONS, list);
	}

	public static Session getSession() {
		Subject currentUser = SecurityUtils.getSubject();
		Session session = currentUser.getSession();

		return session;
	}

	/**
	 * 加密
	 * @param password 加密前密码
	 * @param salt 盐值
	 * @return
	 */
	public static String addPass(String password,String salt){
		//加密算法
		Object object = new SimpleHash("MD5", password, salt, UserConstants.HASH_ITERATIONS);
		String pwd = object.toString();
		return pwd;
	}

	public static void main(String[] args) {
		System.out.println(addPass("123456", "qwer"));
	}

	/**
	 * 手机号脱敏处理
	 * @param mobile
	 * @return
	 */
	public static String changeMobile(String mobile){
		String newMobile = mobile.substring(0, 3) + "****" + mobile.substring(7, mobile.length());
		return newMobile;
	}

	/**
	 * 名字脱敏处理
	 * @param name
	 * @return
	 */
	public static String changeUserName(String name){
		int len = name.length();
		String newName = "";
		//2个字，名字的处理
		if(len == 2){
			newName = name.substring(0, 1) + "*";
		}else{
			newName = name.substring(0, 1) + "*" + name.substring(2, name.length());
		}
		return newName;
	}
}
